﻿using System;
using System.Collections.Generic;
using MedicalCare.DbLayer.Adaptors;
using MedicalCare.EntityDefinitions.Entities;
using MedicalCare.Utilities;
using StructureMap;
using MedicalCare.Messages;
using System.Web.UI.WebControls;

namespace MedicalCare.Admin
{
    public partial class UserDetail : System.Web.UI.Page
    {
        private IUserAdaptor _userAdaptor;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var action = Request.Params["action"];
                if(null == action ||  ActionType.NEW.ToString().Equals(action)) // New
                {
                    Reset(); // 
                }
                else 
                {
                    // TODO: Edit user info
                }

                loadUserRoleList();
                loadProvinceList();
                loadCityList();
                loadDistrictList();

                if (!String.Equals(UserType.USER.ToString(), ddlUserRole.SelectedItem.Value.Trim(), StringComparison.CurrentCultureIgnoreCase))
                    btnAddMore.Visible = false;

                //2013/1/7
                var family = new List<FamilyMessage>();
                FamilyList.DataSource = family;
                FamilyList.DataBind();
            }
        }
        //Champion 2013/1/5
        private void loadUserRoleList()
        {
            _userAdaptor = ObjectFactory.GetInstance<IUserAdaptor>();
            var rolelist = _userAdaptor.GetAllUserRole();
            ddlUserRole.DataTextField = "Name";
            ddlUserRole.DataValueField = "Code";
            ddlUserRole.DataSource = rolelist;
            ddlUserRole.DataBind();
        }
        //Champion 2013/1/5
        private void loadProvinceList()
        {
            _userAdaptor = ObjectFactory.GetInstance<IUserAdaptor>();
            var Provincelist = _userAdaptor.GetAllProvince();
            ddlProvince.DataTextField = "Name";
            ddlProvince.DataValueField = "Id";
            ddlProvince.DataSource = Provincelist;
            ddlProvince.DataBind();
            ddlProvince.SelectedValue = "9";
        }
        //Champion 2013/1/5
        private void loadDistrictList()
        {
            _userAdaptor = ObjectFactory.GetInstance<IUserAdaptor>();
            var Districtlist = _userAdaptor.GetDistrictListByCityId(3);
            ddlDistrict.DataTextField = "DisName";
            ddlDistrict.DataValueField = "Id";
            ddlDistrict.DataSource = Districtlist;
            ddlDistrict.DataBind();
            ddlDistrict.SelectedValue = "49";
        }
        //Champion 2013/1/5
        private void loadCityList()
        {
            _userAdaptor = ObjectFactory.GetInstance<IUserAdaptor>();
            var Citylist = _userAdaptor.GetCityListByProId(9);
            ddlcity.DataTextField = "CityName";
            ddlcity.DataValueField = "CityId";
            ddlcity.DataSource = Citylist;
            ddlcity.DataBind();
            ddlcity.SelectedValue = "2";
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var userAdaptor = ObjectFactory.GetInstance<IUserAdaptor>();
            var familyAdaptor = ObjectFactory.GetInstance<IFamilyAdaptor>();

            var userMsg = GetUserMainData();
            var userid = userAdaptor.Update(userMsg);

            if (String.Equals(UserType.USER.ToString(), ddlUserRole.SelectedItem.Value.Trim(), StringComparison.CurrentCultureIgnoreCase))
            {
                //userMsg.Family = GetFamilyData();
                foreach (var family in userMsg.Family)
                {
                    var familyid = familyAdaptor.Update(family);

                    var mappingMsg = new UserFamilyMappingMessage()
                    {
                        FamilyId = familyid,
                        UserId = userid,
                        CreateUser = AppPage.CurrentUser.UserName
                    };
                    familyAdaptor.InsertFamilyUserMapping(mappingMsg);

                    foreach (var equip in family.Equipments)
                    {
                        var equipFamilyMappingMsg = new EquipmentFamilyMappingMessage()
                                                       {
                                                           FamilyId = familyid,
                                                           EquipmentId = equip.Id,
                                                           CreateUser = AppPage.CurrentUser.UserName
                                                       };
                        familyAdaptor.InsertEquipmentFamilyMapping(equipFamilyMappingMsg);
                    }

                }
            }

            Server.Transfer("~/Admin/UserList.aspx");
            // TODO: 提示保存成功或者失败
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            //Reset();
            Server.Transfer("~/Admin/UserList.aspx");
        }

        //protected void btnAddFamily_Click(object sender, EventArgs e)
        //{
        //    if (String.Equals(UserType.USER.ToString(), ddlUserRole.SelectedItem.Value.Trim(), StringComparison.CurrentCultureIgnoreCase))
        //    {
        //        pnlFamily.Visible = true;
        //        InitialEquipmentType();
        //        InitialEquipments();
        //    }
        //}

        protected void btnGetAllFamily_Click(object sender, EventArgs e)
        {
            var currentFamily = getCurrentFamilyData();
        }

        protected void FamilyList_ItemCommand(object source, DataListCommandEventArgs e)
        {
            try
            {
                var index = Convert.ToInt32(e.CommandArgument);
                switch (e.CommandName.ToLower())
                {
                    case "del":
                        var currentFamily = getFamilyDataAfterDel(index);
                        FamilyList.DataSource = currentFamily;
                        FamilyList.DataBind();
                        break;
                    default:
                        break;
                }
            }
            catch
            {

            }
        }

        private List<FamilyMessage> getFamilyDataAfterDel(int flag)
        {
            var family = new List<FamilyMessage>();
            var index = default(int);
            foreach (var item in FamilyList.Items)
            {
                index++;
                if (flag == index)
                    continue;
                family.Add(new FamilyMessage()
                {
                    Index = index,
                    Name = ((TextBox)((DataListItem)item).FindControl("tbFamilyName")).Text,
                    Age = Convert.ToInt32(
                            ((TextBox)((DataListItem)item).FindControl("tbFamilyAge")).Text),
                }
                        );
            }
            return family;
        }



        //private void InitialEquipmentType()
        //{
        //    var equipTypeAdaptor = ObjectFactory.GetInstance<IEquipmentTypeAdaptor>();
        //    ddlEquimentType.DataTextField = "Name";
        //    ddlEquimentType.DataValueField = "Id";
        //    ddlEquimentType.DataSource = equipTypeAdaptor.GetAllEquipmentType();
        //    ddlEquimentType.DataBind();
        //}

        //private void InitialEquipments()
        //{
        //    try
        //    {
        //        var message = new EquipmentTypeMessage()
        //                          {
        //                              Id = Convert.ToInt32(ddlEquimentType.SelectedValue)
        //                          };

        //        var equipsAdaptor = ObjectFactory.GetInstance<IEquipmentsAdaptor>();
        //        ddlEquipments.DataTextField = "SensorId";
        //        ddlEquipments.DataValueField = "Id";
        //        ddlEquipments.DataSource = equipsAdaptor.GetAllEquipments(message);
        //        ddlEquipments.DataBind();
        //        ddlEquipments.SelectedIndex = -1;
        //    }catch
        //    {
                
        //    }
        //}

        protected void btnFamilyCancel_Click(object sender, EventArgs e)
        {
            pnlFamily.Visible = false;
        }

        private UserMessage GetUserMainData()
        {
            var userAddrMsg = new AddressMessage()
            {
                Province = ddlProvince.SelectedItem.Text,
                City = ddlcity.SelectedItem.Text,
                District = ddlDistrict.SelectedItem.Text,
                AddressDetail = tbAddressDetail.Text,
                PostalCode = tbUserPostalCode.Text.ToString()
            };

            var userMsg = new UserMessage()
            {
                UserAddress = userAddrMsg,
                Age = Convert.ToInt32(tbUserAage.Text.ToString()),
                UserName = tbUserName.Text.ToString(),
                UserRoleCode = ddlUserRole.SelectedItem.Value.ToString(),
                IDNumber = tbUserIDNumber.Text.ToString(),
                Gender = rblUserGender.SelectedItem.Text.ToString(),
                Mobile = tbUserMobile.Text.ToString(),
                Email = tbUserEmail.Text.ToString(),
                QQ = tbUserQQ.Text.ToString(),
                Comment = tbUserComment.Text.ToString(),
                Valid = rblStatus.SelectedItem.Value.ToString(),
                CreateDT = DateTime.Now,
                CreateUser = AppPage.CurrentUser.UserName,
                ModifyDT = DateTime.Now,
                ModifyUser = AppPage.CurrentUser.UserName,
                Id = 0,
            };

            return userMsg;
        }

        //private List<FamilyMessage> GetFamilyData()
        //{
        //    var familylist = new List<FamilyMessage>();

        //    //TODO: Get all family by using loop
        //    var familyAddrMsg = new AddressMessage()
        //                        {
        //                            City = ddlcity.SelectedItem.Text.ToString(),
        //                            PostalCode = tbUserPostalCode.Text.ToString(),
        //                            Province = ddlProvince.SelectedItem.Text.ToString(),
        //                            District = ddlDistrict.SelectedItem.Text.ToString(),
        //                            AddressDetail = tbAddressDetail.Text.ToString()
        //                        };
        //    var euqipMsg = GetEquipments();

        //    var familyMsg = new FamilyMessage()
        //                        {
        //                            Age = Convert.ToInt32(tbFamilyAge.Text),
        //                            Name = tbFamilyName.Text.ToString(),
        //                            Gender = rblFamilyGender.SelectedItem.Value.ToString(),
        //                            MedicalHistory = tbMedicalHistory.Value.ToString(),
        //                            FamilyAddress = familyAddrMsg,
        //                            Equipments = euqipMsg,
        //                            CreateDT = DateTime.Now,
        //                            CreateUser = AppPage.CurrentUser.UserName,
        //                            ModifyDT = DateTime.Now,
        //                            ModifyUser = AppPage.CurrentUser.UserName
        //                        };
        //    familylist.Add(familyMsg);
        //    //

        //    return familylist;
        //}

        private List<FamilyMessage> getCurrentFamilyData()
        {
            var family = new List<FamilyMessage>();
            var index = default(int);
            foreach (var item in FamilyList.Items)
            {
                index++;
                family.Add(


                new FamilyMessage()
                {
                    Index = index,
                    Name = ((TextBox)((DataListItem)item).FindControl("tbFamilyName")).Text,
                    Age = Convert.ToInt32(((TextBox)((DataListItem)item).FindControl("tbFamilyAge")).Text),
                    Gender = ((RadioButtonList)((DataListItem)item).FindControl("rblFamilyGender")).SelectedValue,
                    FamilyAddress = new AddressMessage() 
                        {
                            PostalCode = ((TextBox)((DataListItem)item).FindControl("tbFamilyName")).Text,
                        }
                }
                );
            }
            return family;
        }

        private List<EquipmentsMessage> GetEquipments()
        {
            var equiplist = new List<EquipmentsMessage>();
            try
            {
                var equipMsg = new EquipmentsMessage()
                                   {
                                       //Id = Convert.ToInt32(ddlEquipments.SelectedValue)
                                   };

                equiplist.Add(equipMsg);
                return equiplist;
            }catch
            {
                return null;
            }
        }

        private void Reset()
        {
            tbUserIDNumber.Text = string.Empty;
            tbUserName.Text = string.Empty;
            tbUserAage.Text = string.Empty;
            tbUserMobile.Text = string.Empty;
            tbUserEmail.Text = string.Empty;
            tbUserQQ.Text = string.Empty;
            tbUserPostalCode.Text = string.Empty;
            tbUserComment.Text = string.Empty;
            pnlFamily.Visible = false;
        }

        protected void ddlUserRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!String.Equals(UserType.USER.ToString(), ddlUserRole.SelectedItem.Value.Trim(), StringComparison.CurrentCultureIgnoreCase))
            {
                pnlFamily.Visible = false;
                btnAddMore.Visible = false;
            }
            else
            {
                btnAddMore.Visible = true;
            }
        }

        protected void ddlEquimentType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //InitialEquipments();
        }
        //Champion 2013/1/5
        protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            _userAdaptor = ObjectFactory.GetInstance<IUserAdaptor>();
            var Citylist = _userAdaptor.GetCityListByProId(Convert.ToInt32(ddlProvince.SelectedValue));
            ddlcity.DataTextField = "CityName";
            ddlcity.DataValueField = "CityId";
            ddlcity.DataSource = Citylist;
            ddlcity.DataBind();

            _userAdaptor = ObjectFactory.GetInstance<IUserAdaptor>();
            var Districtlist = _userAdaptor.GetDistrictListByCityId(Convert.ToInt32(ddlcity.SelectedValue));
            ddlDistrict.DataTextField = "DisName";
            ddlDistrict.DataValueField = "Id";
            ddlDistrict.DataSource = Districtlist;
            ddlDistrict.DataBind();
        }
        //Champion 2013/1/5
        protected void ddlcity_SelectedIndexChanged(object sender, EventArgs e)
        {
            _userAdaptor = ObjectFactory.GetInstance<IUserAdaptor>();
            var Districtlist = _userAdaptor.GetDistrictListByCityId(Convert.ToInt32(ddlcity.SelectedValue));
            ddlDistrict.DataTextField = "DisName";
            ddlDistrict.DataValueField = "Id";
            ddlDistrict.DataSource = Districtlist;
            ddlDistrict.DataBind();
        }

        protected void btnAddMore_Click(object sender, EventArgs e)
        {
            var currentFamily = getCurrentFamilyData();
            //index start from 1
            currentFamily.Add(new FamilyMessage() { Index = currentFamily.Count + 1, Name = "" });
            FamilyList.DataSource = currentFamily;
            FamilyList.DataBind();
        }

    }
}